package com.yangguang.huahui.ui.adapters;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.SparseIntArray;
import android.view.View;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.SectionIndexer;

import com.hyphenate.easeui.adapter.EaseContactAdapter;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.widget.EaseAlertDialog;
import com.hyphenate.util.EMLog;
import com.hyphenate.util.HanziToPinyin;
import com.yangguang.huahui.R;
import com.yangguang.huahui.entity.Contact;
import com.yangguang.huahui.entity.DataInfo;
import com.yangguang.huahui.entity.HttpResult;
import com.yangguang.huahui.listadpter.CommonAdapter;
import com.yangguang.huahui.listadpter.ViewHolder;
import com.yangguang.huahui.mvp.model.NewsModel;
import com.yangguang.huahui.rx.RxManager;
import com.yangguang.huahui.rx.RxSubscriber;
import com.yangguang.huahui.ui.activitys.ChatActivity;
import com.yangguang.huahui.utils.ImageLoader;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/3/23.
 */

public class ContactAdapter extends CommonAdapter<Contact.ListBean> implements SectionIndexer {
    List<String> list;
    List<Contact.ListBean> userList;
    List<Contact.ListBean> copyUserList;
    private SparseIntArray positionOfSection;
    private SparseIntArray sectionOfPosition;

    private MyFilter myFilter;
    private boolean notiyfyByFilter;
    public ContactAdapter(Context context, List<Contact.ListBean> data, int layoutId) {
        super(context, data, layoutId);
        copyUserList = new ArrayList<Contact.ListBean>();
        copyUserList.addAll(data);

    }

    public void setNewData(List<Contact.ListBean> data){
        mDatas = data;
        notifyDataSetChanged();
    }

    @Override
    public void convert(final ViewHolder holder, final Contact.ListBean user) {
        user.setUserInitialLetter(user);
        final String username = user.getNickname();
        String header = user.getInitialLetter();
        if (holder.getPosition() == 0 || header != null && !header.equals(getItem(holder.getPosition() - 1).getInitialLetter())) {
            if (TextUtils.isEmpty(header)) {
                holder.setVisible(R.id.header, true);
            } else {
                holder.setVisible(R.id.header, true);
                holder.setText(R.id.header, header);
            }
        } else {
            holder.setVisible(R.id.header, false);
        }
        ImageLoader.loadCircle(mContext, user.getAvatar(), (ImageView) holder.getView(R.id.iv_head));
        holder.setText(R.id.tv_name, user.getNickname());
        holder.getConvertView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mContext.startActivity(new Intent(mContext, ChatActivity.class).putExtra("userId", user.getTo_uid()));
            }
        });
        holder.getConvertView().setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                new EaseAlertDialog(mContext, com.hyphenate.easeui.R.string.delete, com.hyphenate.easeui.R.string.Delete_the_contact, null, new EaseAlertDialog.AlertDialogUser() {
                    @Override
                    public void onResult(boolean confirmed, Bundle bundle) {
                        if (!confirmed) {
                            return;
                        }
                        RxManager.getInstance().doSubscribe(new NewsModel().delete_friend(DataInfo.TOKEN, user.getTo_uid()), new RxSubscriber<HttpResult>(false) {
                            @Override
                            protected void _onNext(HttpResult httpResult) {
                                mDatas.remove(holder.getPosition());
                                notifyDataSetChanged();
                            }

                            @Override
                            protected void _onError() {

                            }
                        });
                    }
                }, true).show();
                return false;
            }
        });
    }

    @Override
    public Contact.ListBean getItem(int position) {
        return super.getItem(position);
    }

    public Filter getFilter() {
        if(myFilter==null){
            myFilter = new MyFilter(mDatas);
        }
        return myFilter;
    }

    public class  MyFilter extends Filter {
        List<Contact.ListBean> mOriginalList = null;

        public MyFilter(List<Contact.ListBean> myList) {
            this.mOriginalList = myList;
        }

        @Override
        protected synchronized FilterResults performFiltering(CharSequence prefix) {
            FilterResults results = new FilterResults();
            if (mOriginalList == null) {
                mOriginalList = new ArrayList<Contact.ListBean>();
            }

            if (prefix == null || prefix.length() == 0) {
                results.values = copyUserList;
                results.count = copyUserList.size();
            } else {
                String prefixString = prefix.toString();
                final int count = mOriginalList.size();
                final ArrayList<Contact.ListBean> newValues = new ArrayList<Contact.ListBean>();
                for (int i = 0; i < count; i++) {
                    final Contact.ListBean user = mOriginalList.get(i);
                    String username = user.getNickname();

                    if (username.startsWith(prefixString)) {
                        newValues.add(user);
                    } else {
                        final String[] words = username.split(" ");
                        final int wordCount = words.length;

                        // Start at index 0, in case valueText starts with space(s)
                        for (String word : words) {
                            if (word.startsWith(prefixString)) {
                                newValues.add(user);
                                break;
                            }
                        }
                    }
                }
                results.values = newValues;
                results.count = newValues.size();
            }
            return results;
        }
        @Override
        protected synchronized void publishResults(CharSequence constraint,
                                                   FilterResults results) {
            userList.clear();
            userList.addAll((List<Contact.ListBean>)results.values);
            if (results.count > 0) {
                notiyfyByFilter = true;
                notifyDataSetChanged();
                notiyfyByFilter = false;
            } else {
                notifyDataSetInvalidated();
            }
        }
    }

    @Override
    public Object[] getSections() {
        positionOfSection = new SparseIntArray();
        sectionOfPosition = new SparseIntArray();
        int count = getCount();
        list = new ArrayList<String>();
        list.add(mContext.getString(com.hyphenate.easeui.R.string.search_header));
        positionOfSection.put(0, 0);
        sectionOfPosition.put(0, 0);
        for (int i = 1; i < count; i++) {

            String letter = getItem(i).getInitialLetter();
            int section = list.size() - 1;
            if (list.get(section) != null && !list.get(section).equals(letter)) {
                list.add(letter);
                section++;
                positionOfSection.put(section, i);
            }
            sectionOfPosition.put(i, section);
        }
        return list.toArray(new String[list.size()]);
    }

    @Override
    public int getPositionForSection(int section) {
        return positionOfSection.get(section);
    }

    @Override
    public int getSectionForPosition(int position) {
        return sectionOfPosition.get(position);
    }


    @Override
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
        if(!notiyfyByFilter){
            copyUserList.clear();
            copyUserList.addAll(userList);
        }
    }
}
